//
//  StatusListViewModel.swift
//  Weibo
//
//  Created by niqiang on 16/7/6.
//  Copyright © 2016年 niqiang. All rights reserved.
//

import Foundation

//微博数据列表视图模型

//如果是KVC模式需要继承NSObject
//用MVVM模式 此类只是包装一些代码逻辑（即写一些函数），不用任何父类
//MVVM好处：更加轻量级  OC一律都继承nsobject

//此处作用 负责微博的数据处理

//上拉刷新最大尝试次数
private let maxPullupTryTimes = 3

class WBStatusListViewModel {
    // 微博模型数组懒加载
    lazy var statusList = [WBStatus]()
    
    //上拉刷新错误次数
    private var pullupErrorTimes = 0
    
    //加载微博列表
    func loadStatus(pullup: Bool,completion: (isSuccess: Bool,shouldRefresh: Bool) -> ()) {
        
        //判断是否上拉刷新，同时检测刷新错误
        if pullup && pullupErrorTimes > maxPullupTryTimes {
            completion(isSuccess: true, shouldRefresh: false)
            
            return
        }
        
        //since_id为取出数组中第一条微博的id
        let since_id = pullup ? 0 : (statusList.first?.id ?? 0)
        let max_id = !pullup ? 0 : (statusList.last?.id ?? 0)
        
        
        WBNetworkManager.shared.statusList (since_id: since_id, max_id: max_id) { (list, isSuccess) in
            //1字典转模型
            guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else {
                
                completion(isSuccess: isSuccess,shouldRefresh: false)
                return
            }
            //            print(list)
            //            print(array)
            //2.拼接数据
            //            self.statusList += array
            //            self.statusList = array + self.statusList
            if pullup {
                //上拉刷新结束后，将结果拼接在数组的末尾
                self.statusList += array
            } else {
                //下拉刷新，应该讲结果数组拼接在数组前面
                self.statusList = array + self.statusList
            }
            
            //3.完成回调 判断上拉刷新的数据量
            //            completion(isSuccess: isSuccess)
            if pullup && array.count == 0{
                self.pullupErrorTimes += 1
                
                completion(isSuccess: isSuccess, shouldRefresh: false)
            } else {
                
                completion(isSuccess: isSuccess, shouldRefresh: true)
            }
        }
    }
}

